package com.hifar.test.syncimport8357.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.abi.utils.minio.MinioCfgUtils;
import com.hifar.abi.utils.minio.MinioUtils;
import com.hifar.abi.utils.zip.ZipUtils;
import com.hifar.config.AsyncConfig;
import com.hifar.fw.json.JsonUtils;
import com.hifar.fw.utils.file.FileUtils;
import com.hifar.fw.utils.file.TextFileUtils;
import com.hifar.fw.utils.id.IdUtils;
import com.hifar.fw.utils.lang.CollectionUtils;
import com.hifar.fw.utils.lang.DateUtils;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.plat.baseModal.pojo.BaseOssFiles;
import com.hifar.plat.baseModal.service.IBaseOssFilesService;
import com.hifar.plat.maindatasource.service.ICollectdbDataSourceService;
import com.hifar.plat.maindatasource.service.IMainDataSourceService;
import com.hifar.plat.officUtil.ExcelTemplateUtil;
import com.hifar.plat.util.AESUtils;
import com.hifar.plat.util.DataDealUtils;
import com.hifar.proj.importdetail.pojo.SysSyncImportDetail;
import com.hifar.proj.importdetail.service.ISysSyncImportDetailService;
import com.hifar.proj.syncimport.pojo.ImportResultVo;
import com.hifar.proj.syncimportdetailerror.pojo.SysSyncImportDetailError;
import com.hifar.proj.syncimportdetailerror.service.ISysSyncImportDetailErrorService;
import com.hifar.sys.*;
import com.hifar.test.syncimport8357.pojo.SysSyncImport8357;
import com.hifar.test.syncimport8357.service.ISysSyncImport8357Service;
import io.minio.ListObjectsArgs;
import io.minio.Result;
import io.minio.messages.Item;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.*;

/**
 * <p>
 * 系统-信息导入表 前端控制器 default
 * </p>
 *
 * @author wangkepeng
 * @since 2024-11-13 17:12:44
 */
@RestController
@RequestMapping("/api/busi/test/sysSyncImport8357Controller")
@Api(tags = "系统-信息导入表功能")
@Slf4j
public class SysSyncImport8357Controller {

    @Value("${spring.datasource.dynamic.datasource.collectdb.url:''}")
    private String collectDBUrl;

    @Autowired
    private ISysSyncImport8357Service sysSyncImport8357Service;

    @Autowired
    private IBaseOssFilesService baseOssFilesService;

    @Autowired
    private IMainDataSourceService mainDataSourceService;

    @Autowired
    private AsyncConfig asynConfig;

    @Autowired
    private ISysSyncImportDetailErrorService sysSyncImportDetailErrorService;

    @Autowired
    private ISysSyncImportDetailService sysSyncImportDetailService;

    @Autowired
    private ICollectdbDataSourceService collectdbDataSourceService;

    @PostMapping(value = "/list")
    @ApiOperation(value = "系统-信息导入表功能:分页查询列表")
    public BusiResponse list(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        QueryWrapper<SysSyncImport8357> queryWrapper = RequestConver.getPostParamRangeDate(pageInfo, "yyyy-mm-dd");
        queryWrapper.orderByDesc("create_time");
        // queryWrapper.in("secret_level",SystemLoginUser.dataSecretSet);
        if (queryWrapper != null && pageInfo.size() > 0) {
            Page<SysSyncImport8357> page = new Page<>((Integer) pageInfo.get("pageNo"),
                    (Integer) pageInfo.get("pageSize"));
            Page<SysSyncImport8357> page1 = sysSyncImport8357Service.page(page, queryWrapper);
            /* 计算分页信息返回给前端 */
            PageResult pageResult = SystemUtil.parsePage(page, page1);
            return BusiResponse.OK(pageResult);
        } else {
            return BusiResponse.error("参数不正确！");
        }
    }

    @PostMapping(value = "/importFile2")
    public BusiResponse importFile2(@RequestBody String importdata) {
        Map<String, Object> dataMap = JSON.parseObject(importdata, Map.class);
        String fileId = StringUtils.trimNull(dataMap.get("fileId"));
        BaseOssFiles ossFile = baseOssFilesService.getById(fileId);


        String importId = IdUtils.uuid32();
        ossFile.setRefId(importId);
        ossFile.setRefType("sys_sync_import");
        baseOssFilesService.updateById(ossFile);


        Date currentDate = new Date();
        SysSyncImport8357 importObj = new SysSyncImport8357();

        importObj.setId(importId);
        importObj.setImportTime(currentDate);
        importObj.setCreateTime(currentDate);
        importObj.setCreateUserId(SystemLoginUser.userId);
        importObj.setCreateUserName(SystemLoginUser.idName);
        importObj.setUpdateTime(currentDate);
        importObj.setUpdateUserId(SystemLoginUser.userId);
        importObj.setUpdateUserName(SystemLoginUser.idName);
        importObj.setImportUserId(SystemLoginUser.userId);
        importObj.setImportUserName(SystemLoginUser.idName);

        //importObj.setExportTime(currentDate);
        //importObj.setExportUserId(SystemLoginUser.userId);
        //importObj.setExportUserName(SystemLoginUser.idName);
        importObj.setFileId(fileId);
        importObj.setFileName(ossFile.getFileName());
        importObj.setFilePath(ossFile.getFilePath());
        importObj.setBucketName(ossFile.getBucketName());
        importObj.setBucketPre(ossFile.getBucketPre());
        // 10未上传20已上传 30已解压 40.数据已导入80出现错误
        importObj.setImportStatus(20);
        sysSyncImport8357Service.save(importObj);
        // 异步执行生成文件的操作
        asynConfig.getAsyncExecutor().execute(() -> {

            String errorMsg = "";
            // 导入状态10未上传20已上传 30已解压 40.数据已导入80出现错误
            importObj.setImportStatus(20);
            String tempPath = getTempPathTest();
            // 导出文件保存路径
            String importSaveDirectory = tempPath + File.separator
                    + DateUtils.formatTime(currentDate, DateUtils.YYYYMMDDHHMMSS);
            FileUtils.mkdirs(importSaveDirectory);

            String zipFilePath = importSaveDirectory + File.separator + ossFile.getFileName();
            String zipFilePath2 = importSaveDirectory + File.separator + "new_" + ossFile.getFileName();
            // 1.将压缩文件下载到本地start
            try {
                MinioUtils.downloadFile(ossFile.getBucketPre(), ossFile.getFilePath(), zipFilePath);
            } catch (Exception e) {
                errorMsg = "双网同步数据导入出现错误,上传文件无法从minio下载！";
                log.error(errorMsg + e.getMessage());
                // TODO Auto-generated catch block
                e.printStackTrace();
                importObj.setImportErrorMsg(errorMsg);
                importObj.setImportStatus(80);
                importObj.setUpdateTime(new Date());
                sysSyncImport8357Service.save(importObj);
                return;
                // return BusiResponse.error("双网同步数据导入出现错误");

            }

            // 1.将压缩文件下载到本地end
            // 2.解压压缩文件 start

            //解压是否成功
            boolean zipStatus = false;
            log.error("====zip文件，第一次解压失败！=======");

            //修复压缩文件 start
            String osName = DataDealUtils.getOsName();
            if (osName.equals("linux")) {
                String command = "zip -F " + zipFilePath + " --out " + zipFilePath2 + ""; // Linux命令
                try {
                    Process process = Runtime.getRuntime().exec(command);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        log.error("打印信息：==" + line);
                    }
                    int exitCode = process.waitFor();
                    log.info("debug==========Exited with error code : " + exitCode);
                    log.info("=====Exited with error code : " + exitCode);
                    if (exitCode == 0) {
                        zipStatus = true;
                        ZipUtils.unZipFiles(zipFilePath2, importSaveDirectory);
                    } else {
                        zipStatus = false;
                    }
                } catch (Exception e2) {
                    zipStatus = false;
                    e2.printStackTrace();
                }

            }
            //修复压缩文件 end
            if (!zipStatus) {
                errorMsg = "文件解压错误！";
                importObj.setImportErrorMsg(errorMsg);
                importObj.setImportStatus(80);
                importObj.setUpdateTime(new Date());
                sysSyncImport8357Service.save(importObj);
                return;
            }


            // 2.解压压缩文件 end
            // 3.读取db文件内容，并生成sql语句。 start
            String dbDirectory = importSaveDirectory + File.separator + "db";
            FileUtils.mkdirs(dbDirectory);

            List<String> dbFilePathList = FileUtils.getChildFilesList(dbDirectory);
            String dbFileContent = "";
            String decryptContent = "";
            String encryptKey = AESUtils.getSysConfigKey();
            Boolean runRight = null;
            Boolean allRight = true;
            SysSyncImportDetail importDetail = null;
            String detailId = null;
            ImportResultVo retVo = null;
            for (String path : dbFilePathList) {
                // 3.1插入数据 start
                dbFileContent = TextFileUtils.getTexFileContent(path);
                //System.out.println("====dbFileContent=====##" + dbFileContent);
                decryptContent = AESUtils.decryptString(encryptKey, dbFileContent);
                //System.out.println("====decryptContent=====##" + decryptContent);
                detailId = IdUtils.uuid32();

                retVo = dealOneTableJsonData(decryptContent, detailId, importId);
                runRight = retVo.isRunRight();
                if (!runRight) {
                    allRight = false;
                }
                // 3.1插入数据 end
                // 3.2查询导入明细数据start
                importDetail = new SysSyncImportDetail();
                importDetail.setId(detailId);
                importDetail.setMainId(importId);
                importDetail.setInfoType(1);
                importDetail.setFileName(path.replaceAll(dbDirectory, ""));
                importDetail.setCreateTime(currentDate);
                importDetail.setCreateUserId(SystemLoginUser.userId);
                importDetail.setCreateUserName(SystemLoginUser.idName);
                importDetail.setUpdateTime(currentDate);
                importDetail.setUpdateUserId(SystemLoginUser.userId);
                importDetail.setUpdateUserName(SystemLoginUser.idName);
                importDetail.setTableName(retVo.getTableName());
                if (runRight) {
                    importDetail.setStatus("1");

                } else {
                    importDetail.setStatus("2");
                }
                sysSyncImportDetailService.save(importDetail);
                // 3.2查询导入明细数据end
            }
            // 3.读取db文件内容，并生成sql语句。 end
//====================================================================================================================================================================
            // 4.读取minio文件，并导入minio中。 start
            // 加密文件路径
            String encryptFileDirectory = importSaveDirectory + File.separator + "fileencrypt";
            // 解密后的文件路径
            String decryptFileDirectory = importSaveDirectory + File.separator + "filedecrypt";
            FileUtils.mkdirs(decryptFileDirectory);
            // 运行正确
            runRight = true;
            // 4.2查询导入明细数据 start
            importDetail = new SysSyncImportDetail();
            importDetail.setMainId(detailId);
            importDetail.setInfoType(2);
            importDetail.setFileName(ossFile.getFileName());
            importDetail.setCreateTime(currentDate);
            importDetail.setCreateUserId(SystemLoginUser.userId);
            importDetail.setCreateUserName(SystemLoginUser.idName);
            importDetail.setUpdateTime(currentDate);
            importDetail.setUpdateUserId(SystemLoginUser.userId);
            importDetail.setUpdateUserName(SystemLoginUser.idName);
            importDetail.setTableName(retVo.getTableName());
            if (runRight) {
                importDetail.setStatus("1");
            } else {
                importDetail.setStatus("2");
            }
            sysSyncImportDetailService.save(importDetail);
            // 4.2 查询导入明细数据 end
            // 4.3 解密文件，然后导入到minio start
            List<String> minioFileEncryptPathList = FileUtils.getChildFilesList(encryptFileDirectory);
            String bucketName = "";
            // 操作系统的文件路径
            String minioFilePathSystem = "";
            // 数据库的文件路径
            String minioFilePathDb = "";

            String decryptFilePath = "";
            String encryptFileRelativePath = "";
            String temp = "";
            File decryptFile = null;
            for (String encryptPath : minioFileEncryptPathList) {
                encryptFileRelativePath = encryptPath.substring(encryptFileDirectory.length());
                temp = encryptFileRelativePath.substring(1);
                bucketName = temp.substring(0, temp.indexOf(File.separator));
                minioFilePathSystem = temp.substring(bucketName.length());

                if ("\\".equals(File.separator)) {
                    minioFilePathDb = minioFilePathSystem.replaceAll("\\\\", "/");
                } else {
                    minioFilePathDb = minioFilePathSystem;
                }
                // 4.3.1 解密文件
//				decryptFilePath=decryptFileDirectory+File.separator+bucketName+minioFilePathSystem;
//				cn.hutool.core.io.FileUtil.touch(decryptFilePath);
//				try {
//					AESUtils.decryptFile(encryptPath, decryptFilePath);
//				} catch (Exception e) {
//					
//					e.printStackTrace();
//				}
                // MinioUtils.uploadLocalFileToMinio(bucketName, minioFilePathDb,
                // decryptFilePath);
                // 4.3.2 上传到minio
                try {
                    //log.error("=====bucketName=====" + bucketName);
                    //log.error("=====minioFilePathDb=====" + minioFilePathDb);
                    //log.error("=====encryptPath=====" + encryptPath);
                    MinioUtils.uploadFileToMinioByStreamEncryptFile(bucketName, minioFilePathDb, encryptPath);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                // todo:正式运行添加删除解密文件的代码start
                // 4.3.3 删除文件
                // decryptFile=new File(decryptFilePath);
                // if(decryptFile.exists()) {
                // decryptFile.delete();
                // }
                // todo:正式运行添加删除解密文件的代码end

            }
            // 4.3 解密文件，然后导入到minio end

            // 4.读取minio文件，并导入minio中。 end
//====================================================================================================================================================================
            if (allRight) {
                importObj.setImportStatus(40);
            } else {
                importObj.setImportStatus(80);
            }

            sysSyncImport8357Service.saveOrUpdate(importObj);
            log.error("======#####################################导入完成##############################################");
            log.error("-----------------------------关联任务成功----------------------------------------------------------");

        });

        return BusiResponse.ok("成功");

    }

    @PostMapping(value = "/importFile")
    @ApiOperation(value = "系统-信息导入表功能:分页查询列表")
    public BusiResponse importFile(@RequestBody String importdata) {
        Map<String, Object> dataMap = JSON.parseObject(importdata, Map.class);
        String fileId = StringUtils.trimNull(dataMap.get("fileId"));
        BaseOssFiles ossFile = baseOssFilesService.getById(fileId);


        String importId = IdUtils.uuid32();
        ossFile.setRefId(importId);
        ossFile.setRefType("sys_sync_import");
        baseOssFilesService.updateById(ossFile);


        Date currentDate = new Date();
        SysSyncImport8357 importObj = new SysSyncImport8357();

        importObj.setId(importId);
        importObj.setImportTime(currentDate);
        importObj.setCreateTime(currentDate);
        importObj.setCreateUserId(SystemLoginUser.userId);
        importObj.setCreateUserName(SystemLoginUser.idName);
        importObj.setUpdateTime(currentDate);
        importObj.setUpdateUserId(SystemLoginUser.userId);
        importObj.setUpdateUserName(SystemLoginUser.idName);
        importObj.setImportUserId(SystemLoginUser.userId);
        importObj.setImportUserName(SystemLoginUser.idName);

        //importObj.setExportTime(currentDate);
        //importObj.setExportUserId(SystemLoginUser.userId);
        //importObj.setExportUserName(SystemLoginUser.idName);
        importObj.setFileId(fileId);
        importObj.setFileName(ossFile.getFileName());
        importObj.setFilePath(ossFile.getFilePath());
        importObj.setBucketName(ossFile.getBucketName());
        importObj.setBucketPre(ossFile.getBucketPre());
        // 10未上传20已上传 30已解压 40.数据已导入80出现错误
        importObj.setImportStatus(20);
        sysSyncImport8357Service.save(importObj);
        // 异步执行生成文件的操作
        asynConfig.getAsyncExecutor().execute(() -> {

            String errorMsg = "";
            // 导入状态10未上传20已上传 30已解压 40.数据已导入80出现错误
            importObj.setImportStatus(20);
            String tempPath = getTempPathTest();
            // 导出文件保存路径
            String importSaveDirectory = tempPath + File.separator
                    + DateUtils.formatTime(currentDate, DateUtils.YYYYMMDDHHMMSS);
            FileUtils.mkdirs(importSaveDirectory);

            String zipFilePath = importSaveDirectory + File.separator + ossFile.getFileName();
            String zipFilePath2 = importSaveDirectory + File.separator + "new_" + ossFile.getFileName();
            // 1.将压缩文件下载到本地start
            try {
                MinioUtils.downloadFile(ossFile.getBucketPre(), ossFile.getFilePath(), zipFilePath);
            } catch (Exception e) {
                errorMsg = "双网同步数据导入出现错误,上传文件无法从minio下载！";
                log.error(errorMsg + e.getMessage());
                // TODO Auto-generated catch block
                e.printStackTrace();
                importObj.setImportErrorMsg(errorMsg);
                importObj.setImportStatus(80);
                importObj.setUpdateTime(new Date());
                sysSyncImport8357Service.save(importObj);
                return;
                // return BusiResponse.error("双网同步数据导入出现错误");

            }

            // 1.将压缩文件下载到本地end
            // 2.解压压缩文件 start
            try {
                ZipUtils.unZipFiles(zipFilePath, importSaveDirectory);
            } catch (Exception e) {
                //解压是否成功
                boolean zipStatus = false;
                log.error("===484=====zip文件，第一次解压失败！=======");
                e.printStackTrace();
                //修复压缩文件 start
                String osName = DataDealUtils.getOsName();
                if (osName.equals("linux")) {
                    String command = "zip -F " + zipFilePath + " --out " + zipFilePath2 + ""; // Linux命令
                    try {
                        Process process = Runtime.getRuntime().exec(command);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                        String line;
                        while ((line = reader.readLine()) != null) {
                            log.error("====linux系统zip修复的shell执行过程：==" + line);
                        }
                        int exitCode = process.waitFor();
                        log.info("===linux系统zip修复的shell的返回 code : " + exitCode);
                        log.error("=====linux系统zip修复的shell的返回 code :" + exitCode);
                        if (exitCode == 0) {

                            try {
                                ZipUtils.unZipFiles(zipFilePath2, importSaveDirectory);
                                zipStatus = true;
                                log.error("=====linux系统zip修复的文件加压完成！");
                            } catch (Exception e1) {
                                e1.printStackTrace();
                                errorMsg = "zip文件二次解压异常！";
                                importObj.setImportErrorMsg(errorMsg);
                                importObj.setImportStatus(80);
                                importObj.setUpdateTime(new Date());
                                sysSyncImport8357Service.save(importObj);
                                return;

                            }
                        } else {
                            zipStatus = false;
                        }
                    } catch (Exception e2) {
                        zipStatus = false;
                        e2.printStackTrace();
                    }

                }
                //修复压缩文件 end
                if (!zipStatus) {
                    errorMsg = "文件解压错误！";
                    importObj.setImportErrorMsg(errorMsg);
                    importObj.setImportStatus(80);
                    importObj.setUpdateTime(new Date());
                    sysSyncImport8357Service.save(importObj);
                    return;
                }


            }
            // 2.解压压缩文件 end
            // 3.读取db文件内容，并生成sql语句。 start
            String dbDirectory = importSaveDirectory + File.separator + "db";
            FileUtils.mkdirs(dbDirectory);

            List<String> dbFilePathList = FileUtils.getChildFilesList(dbDirectory);
            String dbFileContent = "";
            String decryptContent = "";
            String encryptKey = AESUtils.getSysConfigKey();
            Boolean runRight = null;
            Boolean allRight = true;
            SysSyncImportDetail importDetail = null;
            String detailId = null;
            ImportResultVo retVo = null;
            for (String path : dbFilePathList) {
                // 3.1插入数据 start
                dbFileContent = TextFileUtils.getTexFileContent(path);
                //System.out.println("====dbFileContent=====##" + dbFileContent);
                decryptContent = AESUtils.decryptString(encryptKey, dbFileContent);
                //System.out.println("====decryptContent=====##" + decryptContent);
                detailId = IdUtils.uuid32();

                retVo = dealOneTableJsonData(decryptContent, detailId, importId);
                runRight = retVo.isRunRight();
                if (!runRight) {
                    allRight = false;
                }
                // 3.1插入数据 end
                // 3.2查询导入明细数据start
                importDetail = new SysSyncImportDetail();
                importDetail.setId(detailId);
                importDetail.setMainId(importId);
                importDetail.setInfoType(1);
                importDetail.setFileName(path.replaceAll(dbDirectory, ""));
                importDetail.setCreateTime(currentDate);
                importDetail.setCreateUserId(SystemLoginUser.userId);
                importDetail.setCreateUserName(SystemLoginUser.idName);
                importDetail.setUpdateTime(currentDate);
                importDetail.setUpdateUserId(SystemLoginUser.userId);
                importDetail.setUpdateUserName(SystemLoginUser.idName);
                importDetail.setTableName(retVo.getTableName());
                if (runRight) {
                    importDetail.setStatus("1");

                } else {
                    importDetail.setStatus("2");
                }
                sysSyncImportDetailService.save(importDetail);
                // 3.2查询导入明细数据end
            }
            // 3.读取db文件内容，并生成sql语句。 end
//====================================================================================================================================================================
            // 4.读取minio文件，并导入minio中。 start
            // 加密文件路径
            String encryptFileDirectory = importSaveDirectory + File.separator + "fileencrypt";
            // 解密后的文件路径
            String decryptFileDirectory = importSaveDirectory + File.separator + "filedecrypt";
            FileUtils.mkdirs(decryptFileDirectory);
            // 运行正确
            runRight = true;
            // 4.2查询导入明细数据 start
            importDetail = new SysSyncImportDetail();
            importDetail.setMainId(detailId);
            importDetail.setInfoType(2);
            importDetail.setFileName(ossFile.getFileName());
            importDetail.setCreateTime(currentDate);
            importDetail.setCreateUserId(SystemLoginUser.userId);
            importDetail.setCreateUserName(SystemLoginUser.idName);
            importDetail.setUpdateTime(currentDate);
            importDetail.setUpdateUserId(SystemLoginUser.userId);
            importDetail.setUpdateUserName(SystemLoginUser.idName);
            importDetail.setTableName(retVo.getTableName());
            if (runRight) {
                importDetail.setStatus("1");
            } else {
                importDetail.setStatus("2");
            }
            sysSyncImportDetailService.save(importDetail);
            // 4.2 查询导入明细数据 end
            // 4.3 解密文件，然后导入到minio start
            List<String> minioFileEncryptPathList = FileUtils.getChildFilesList(encryptFileDirectory);
            String bucketName = "";
            // 操作系统的文件路径
            String minioFilePathSystem = "";
            // 数据库的文件路径
            String minioFilePathDb = "";

            String decryptFilePath = "";
            String encryptFileRelativePath = "";
            String temp = "";
            File decryptFile = null;
            for (String encryptPath : minioFileEncryptPathList) {
                encryptFileRelativePath = encryptPath.substring(encryptFileDirectory.length());
                temp = encryptFileRelativePath.substring(1);
                bucketName = temp.substring(0, temp.indexOf(File.separator));
                minioFilePathSystem = temp.substring(bucketName.length());

                if ("\\".equals(File.separator)) {
                    minioFilePathDb = minioFilePathSystem.replaceAll("\\\\", "/");
                } else {
                    minioFilePathDb = minioFilePathSystem;
                }
                // 4.3.1 解密文件
//				decryptFilePath=decryptFileDirectory+File.separator+bucketName+minioFilePathSystem;
//				cn.hutool.core.io.FileUtil.touch(decryptFilePath);
//				try {
//					AESUtils.decryptFile(encryptPath, decryptFilePath);
//				} catch (Exception e) {
//					
//					e.printStackTrace();
//				}
                // MinioUtils.uploadLocalFileToMinio(bucketName, minioFilePathDb,
                // decryptFilePath);
                // 4.3.2 上传到minio
                try {
                    //log.error("=====bucketName=====" + bucketName);
                    //log.error("=====minioFilePathDb=====" + minioFilePathDb);
                    //log.error("=====encryptPath=====" + encryptPath);
                    MinioUtils.uploadFileToMinioByStreamEncryptFile(bucketName, minioFilePathDb, encryptPath);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                // todo:正式运行添加删除解密文件的代码start
                // 4.3.3 删除文件
                // decryptFile=new File(decryptFilePath);
                // if(decryptFile.exists()) {
                // decryptFile.delete();
                // }
                // todo:正式运行添加删除解密文件的代码end

            }
            // 4.3 解密文件，然后导入到minio end

            // 4.读取minio文件，并导入minio中。 end
//====================================================================================================================================================================
            if (allRight) {
                importObj.setImportStatus(40);
            } else {
                importObj.setImportStatus(80);
            }

            sysSyncImport8357Service.saveOrUpdate(importObj);
            log.error("======#####################################导入完成##############################################");
            log.error("-----------------------------关联任务成功----------------------------------------------------------");

        });

        return BusiResponse.ok("成功");

    }

    public static String createColumnUpdateSqlMysql(Set<String> keySet, String idColumnName) {
        StringBuffer sb = new StringBuffer();
        int i = 0;
        for (String keyStr : keySet) {
            if (!keyStr.equals(idColumnName)) {
                sb.append("`" + StringUtils.fieldToColumn(keyStr) + "`" + "= {" + i + "} ,");
                i++;
            }

        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        return sb.toString();
    }

    public static String createColumnUpdateSqlDm(Set<String> keySet, String idColumnName) {
        StringBuffer sb = new StringBuffer();
        int i = 0;
        for (String keyStr : keySet) {
            if (!keyStr.equals(idColumnName)) {
                sb.append(StringUtils.fieldToColumn(keyStr) + "= {" + i + "} ,");
                i++;
            }

        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        return sb.toString();
    }
    // todo : 正式运行debug设置为false
    // public boolean debug = true;

    private ImportResultVo dealOneTableJsonData(String decryptContent, String detailId, String mainId) {
        ImportResultVo retVo = new ImportResultVo();
        // 运行正常
        Boolean runRight = true;
        List<String> jsonList = CollectionUtils.valueOfList(decryptContent, "αα");
        Map<String, Object> objMap = null;
        Map<String, Object> dataMap = null;
        Map<String, Object> typeMap = null;
        String tableName = "";
        Long oldUpdateTimeLong = null;
        Long newUpdateTimeLong = null;
        Object oldUpdateTimeObj = null;
        Object newUpdateTimeObj = null;

        String newTableName = "";
        Map<String, Object> oldMap = null;
        Map<String, Object> newMap = null;
        String sql = "";
        String newId = "";
        String dataType = "";
        java.sql.Date date1 = null;
        java.sql.Timestamp timestamp1 = null;
        String updateTimeString = null;
        List<Object> paramList = null;
        List<String> paramListString = null;
        String idColumnName = "";
        String updateColumnName = "";
        String datasource = "1";

        String dbType = mainDataSourceService.getDbType();
        int i = 0;
        for (String oneJsonData : jsonList) {
            objMap = JsonUtils.toMap(oneJsonData);
            tableName = StringUtils.trimNull(objMap.get("tableName"));
            datasource = StringUtils.trimNull(objMap.get("datasource"));
            newTableName = tableName;

//			if (debug) { 
//				  newTableName = tableName + "_001"; 
//			} else {
//					  newTableName =  tableName; 
//			}

            newTableName = tableName;
            dataMap = (Map<String, Object>) objMap.get("data");

            if (i == 0) {
                //只有第一行数据，才检查表结构
                //采集表，判断表是否存在，不存在的创建表
                if ("2".equals(datasource)) {
                    String schemaName = getSchemaName(collectDBUrl);
                    sql = "     SELECT  distinct  table_name  "
                            + " FROM DBA_TAB_COLUMNS t where OWNER = '" + schemaName + "'  "
                            + " and (table_name ='" + tableName + "') ";
                    List<Map<String, Object>> collectTableList = collectdbDataSourceService.selectList(sql, null);
                    if (collectTableList == null || collectTableList.size() < 1) {
                        sql = "CREATE TABLE \"" + tableName + "\" "
                                + "("
                                + "\"TAGID\" VARCHAR(32) NOT NULL,"
                                + "\"TAGNAME\" VARCHAR(255) NOT NULL,"
                                + "\"TAGVALUE\" VARCHAR(255) NOT NULL,"
                                + "\"TIMESTAMP\" TIMESTAMP(0) NOT NULL,"
                                + "\"TAGTYPE\" INT NOT NULL,"
                                + "\"ALARMUPPERLIMIT\" VARCHAR(255),"
                                + "\"ALARMLOWERLIMIT\" VARCHAR(255),"
                                + "\"ALARMSTATUS\" INT,"
                                + "\"ALARMINFO\" VARCHAR(4000),"
                                + "\"USERNAME\" VARCHAR2(100),"
                                + "\"REMARKS\" VARCHAR2(100),"
                                + "PRIMARY KEY(\"TAGID\"))  ";
                        collectdbDataSourceService.update(sql);

                    }

                    if ("dameng".equals(dbType)) {
                        //查询是否有 USERNAME
                        sql = "select  c.COLUMN_NAME, d.comments ,t.table_name,d.owner "
                                + "from user_tables t "
                                + "	left join user_tab_columns c on t.TABLE_NAME = c.TABLE_NAME "
                                + "	left join user_col_comments d "
                                + "	on c.COLUMN_NAME = d.COLUMN_NAME and d.owner='" + schemaName + "' "
                                + "		and c.TABLE_NAME = d.TABLE_NAME where t.table_name='" + tableName + "' "
                                + "		and c.column_name='USERNAME' ";
                        List<Map<String, Object>> remarkFieldList = collectdbDataSourceService.selectList(sql, null);
                        if (remarkFieldList == null || remarkFieldList.size() == 0) {
                            sql = "	alter table \"" + tableName + "\" add column \"USERNAME\" VARCHAR2(100)";
                            collectdbDataSourceService.update(sql, null);

                        }

                        try {
                            //查询是否有 remarks
                            sql = "select  c.COLUMN_NAME, d.comments ,t.table_name,d.owner "
                                    + "from user_tables t "
                                    + "	left join user_tab_columns c on t.TABLE_NAME = c.TABLE_NAME "
                                    + "	left join user_col_comments d "
                                    + "	on c.COLUMN_NAME = d.COLUMN_NAME and d.owner='" + schemaName + "' "
                                    + "		and c.TABLE_NAME = d.TABLE_NAME where t.table_name='" + tableName + "' "
                                    + "		and c.column_name='REMARKS' ";
                            List<Map<String, Object>> remarksFieldList = collectdbDataSourceService.selectList(sql, null);
                            if (remarksFieldList == null || remarksFieldList.size() == 0) {
                                sql = "	alter table \"" + tableName + "\" add column \"REMARKS\" VARCHAR2(100)";
                                collectdbDataSourceService.update(sql, null);
                            }
                        } catch (Exception e) {
                            log.error("=====496=表格===：" + tableName + "==添加字段USERNAME,REMARKS出现错误=======");
                            e.printStackTrace();
                        }
                    }
                }
            }
            i++;
            if ("1".equals(datasource)) {
                if (dataMap.keySet().contains("id")) {
                    idColumnName = "id";
                } else if (dataMap.keySet().contains("ID")) {
                    idColumnName = "ID";
                }

            } else if ("2".equals(datasource)) {
                if (dataMap.keySet().contains("tagid")) {
                    idColumnName = "tagid";
                } else if (dataMap.keySet().contains("TAGID")) {
                    idColumnName = "TAGID";
                }
            }

            if ("1".equals(datasource)) {
                if (dataMap.keySet().contains("update_time")) {
                    updateColumnName = "update_time";
                } else if (dataMap.keySet().contains("UPDATE_TIME")) {
                    updateColumnName = "UPDATE_TIME";
                } else if (dataMap.keySet().contains("updateTime")) {
                    updateColumnName = "updateTime";
                }
            } else if ("2".equals(datasource)) {
                if (dataMap.keySet().contains("timestamp")) {
                    updateColumnName = "timestamp";
                } else if (dataMap.keySet().contains("TIMESTAMP")) {
                    updateColumnName = "TIMESTAMP";
                }
            }

            typeMap = (Map<String, Object>) objMap.get("fieldType");
            // 查询新数据是否存在,不存在则插入、存在则判断时间是否大于旧的时间，
            // 大于则更新，小于则不处理
            newId = StringUtils.trimNull(dataMap.get(idColumnName));

            if (dbType.equals("mysql")) {
                if ("1".equals(datasource)) {
                    sql = "select * from `" + newTableName + "` where " + idColumnName + "= {0}  ";
                    log.error("==506==select==sql语句====" + sql);
                    oldMap = mainDataSourceService.selectOne(sql, newId);
                } else if ("2".equals(datasource)) {
                    log.error("==509==select==sql语句====" + sql);
                    sql = "select * from `" + newTableName + "` where " + idColumnName + "= {0}  ";
                    oldMap = collectdbDataSourceService.selectOne(sql, newId);
                }
            } else {
                if ("1".equals(datasource)) {
                    sql = "select * from " + newTableName + " where " + idColumnName + "= {0}  ";
                    log.error("==516==select==sql语句====" + sql);
                    oldMap = mainDataSourceService.selectOne(sql, newId);
                } else if ("2".equals(datasource)) {
                    sql = "select * from \"" + newTableName + "\" where " + idColumnName + "= {0}  ";
                    log.error("==520==select==sql语句====" + sql);
                    oldMap = collectdbDataSourceService.selectOne(sql, newId);
                }

            }

            if (oldMap != null) {
                oldUpdateTimeObj = oldMap.get(updateColumnName);
                if (oldUpdateTimeObj == null) {
                    System.out.println("=======oldUpdateTimeObj==null=============");
                }
                if (oldUpdateTimeObj != null) {
                    dataType = getTypeString(oldUpdateTimeObj.getClass().toString());
                    newUpdateTimeObj = dataMap.get(updateColumnName);
                    if (dataType.equals("datatime")) {
                        date1 = (java.sql.Date) oldUpdateTimeObj;
                        oldUpdateTimeLong = date1.getTime();
                        updateTimeString = StringUtils.trimNull(newUpdateTimeObj);
                        //newUpdateTimeLong = DateUtils.paseTime(updateTimeString, DateUtils.YYYY_MM_DD_HH_MM_SS).getTime();
                        newUpdateTimeLong = parseTime(updateTimeString);
                    } else if (dataType.equals("date")) {

                        date1 = (java.sql.Date) oldUpdateTimeObj;
                        oldUpdateTimeLong = date1.getTime();
                        updateTimeString = StringUtils.trimNull(newUpdateTimeObj);
                        //newUpdateTimeLong = DateUtils.paseTime(updateTimeString, DateUtils.YYYY_MM_DD_HH_MM_SS).getTime();
                        newUpdateTimeLong = parseTime(updateTimeString);

                    } else if (dataType.equals("timestamp")) {
                        timestamp1 = (java.sql.Timestamp) oldUpdateTimeObj;
                        oldUpdateTimeLong = timestamp1.getTime();
                        updateTimeString = StringUtils.trimNull(newUpdateTimeObj);
                        //newUpdateTimeLong = DateUtils.paseTime(updateTimeString, DateUtils.YYYY_MM_DD_HH_MM_SS).getTime();
                        newUpdateTimeLong = parseTime(updateTimeString);
                    } else if (dataType.equals("long")) {
                        oldUpdateTimeLong = (Long) oldUpdateTimeObj;
                        newUpdateTimeLong = (Long) dataMap.get(updateColumnName);
                    }
                }
                // new数据大于old数据的updatetime则更新，否则不更新
                if (newUpdateTimeLong != null && oldUpdateTimeLong != null && newUpdateTimeLong > oldUpdateTimeLong) {
                } else {

                }
                //update1101 start
                paramList = new ArrayList<Object>();
                StringBuffer sb = new StringBuffer();
                if (dbType.equals("mysql")) {
                    sb.append("update `" + newTableName + "`  ");
                    sb.append("  set " + createColumnUpdateSqlMysql(dataMap.keySet(), idColumnName) + " ");
                } else {
                    if ("1".equals(datasource)) {
                        sb.append("update " + newTableName);
                        sb.append("  set " + createColumnUpdateSqlDm(dataMap.keySet(), idColumnName) + " ");
                    } else {
                        sb.append("update \"" + newTableName + "\" ");
                        sb.append("  set " + createColumnUpdateSqlDm(dataMap.keySet(), idColumnName) + " ");
                    }

                }

                sb.append("where " + idColumnName + "={" + (dataMap.keySet().size() - 1) + "} ");
                for (String keyStr : dataMap.keySet()) {
                    if (!keyStr.equals(idColumnName)) {
                        paramList.add(dataMap.get(keyStr));
                    }
                }
                paramList.add(dataMap.get(idColumnName));
                sql = sb.toString();
                // System.out.println("===updatesql==========="+sql);
                try {
                    log.error("====update-sql语句===" + sql);
                    paramListString = new ArrayList<String>();
                    for (Object obj : paramList) {
                        paramListString.add(obj.toString());
                    }

                    log.error("====update-sql参数===" + String.join(",", paramListString));

                    if ("1".equals(datasource)) {
                        mainDataSourceService.update(sql, paramList.toArray());
                    } else if ("2".equals(datasource)) {
                        collectdbDataSourceService.update(sql, paramList.toArray());
                    }
                } catch (Exception e) {

                    // 插入错误数据
                    SysSyncImportDetailError detailError = new SysSyncImportDetailError();
                    detailError.setId(IdUtils.uuid32());
                    detailError.setMainId(mainId);
                    detailError.setDetailId(detailId);
                    detailError.setTableName(newTableName);
                    detailError.setInfoType(1);
                    detailError.setDataInfo(oneJsonData);
                    detailError.setCreateTime(new Date());
                    detailError.setCreateUserId(SystemLoginUser.userId);
                    detailError.setCreateUserName(SystemLoginUser.idName);
                    detailError.setUpdateTime(new Date());
                    detailError.setUpdateUserId(SystemLoginUser.userId);
                    detailError.setUpdateUserName(SystemLoginUser.idName);
                    detailError.setErrorMsg("双网同步,update错误：[" + tableName + "]");
                    sysSyncImportDetailErrorService.save(detailError);

                    e.printStackTrace();
                    runRight = false;
                    log.error("双网同步,update错误：[" + tableName + "]" + oneJsonData);
                }
                //update1101 end

            } else {
                // insert语句
                paramList = new ArrayList<Object>();

                StringBuffer sb = new StringBuffer();


                if (dbType.equals("mysql")) {
                    sb.append("insert into `" + newTableName + "` ");
                    sb.append("(" + createColumnSqlMysql(dataMap.keySet(), dataMap) + ")");
                } else {
                    sb.append("insert into \"" + newTableName + "\"  ");
                    sb.append("(" + createColumnSqlDm(dataMap.keySet(), dataMap) + ")");
                }


                sb.append("values(" + createPrepared(dataMap.keySet().size()) + ")");

                for (String keyStr : dataMap.keySet()) {
                    paramList.add(dataMap.get(keyStr));
                }

                sql = sb.toString();

                try {
                    log.error("====insert-sql语句-===" + sql);
                    paramListString = new ArrayList<String>();
                    for (Object obj : paramList) {
                        paramListString.add(obj.toString());
                    }
                    log.error("====insert-sql参数===" + String.join(",", paramListString));
                    if ("1".equals(datasource)) {
                        mainDataSourceService.insert(sql, paramList.toArray());
                    } else if ("2".equals(datasource)) {
                        collectdbDataSourceService.insert(sql, paramList.toArray());
                    }
                } catch (Exception e) {


                    // 插入错误数据
                    SysSyncImportDetailError detailError = new SysSyncImportDetailError();
                    detailError.setId(IdUtils.uuid32());
                    detailError.setMainId(mainId);
                    detailError.setDetailId(detailId);
                    detailError.setTableName(newTableName);
                    detailError.setInfoType(1);
                    detailError.setDataInfo(oneJsonData);
                    detailError.setCreateTime(new Date());
                    detailError.setCreateUserId(SystemLoginUser.userId);
                    detailError.setCreateUserName(SystemLoginUser.idName);
                    detailError.setUpdateTime(new Date());
                    detailError.setUpdateUserId(SystemLoginUser.userId);
                    detailError.setUpdateUserName(SystemLoginUser.idName);
                    detailError.setErrorMsg("双网同步,insert错误：[" + tableName + "]");
                    sysSyncImportDetailErrorService.save(detailError);

                    log.error("双网同步,insert错误：[" + tableName + "]" + oneJsonData);
                    e.printStackTrace();
                    runRight = false;
                }
            }
            tableName = "";
            oldUpdateTimeLong = null;
            newUpdateTimeLong = null;
            oldUpdateTimeObj = null;
            newUpdateTimeObj = null;
            newTableName = "";
            oldMap = null;
            newMap = null;
            sql = "";

        }
        retVo.setRunRight(runRight);
        retVo.setTableName(newTableName);
        return retVo;
    }

    public static String createColumnSqlMysql(Set<String> keySet, Map<String, Object> dataMap) {
        StringBuffer sb = new StringBuffer();
        for (String keyStr : keySet) {
            // if(!"".equals(dataMap.get(keyStr))) {
            sb.append("`" + StringUtils.fieldToColumn(keyStr) + "`" + ",");
            // }
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        return sb.toString();
    }

    public static String createColumnSqlDm(Set<String> keySet, Map<String, Object> dataMap) {
        StringBuffer sb = new StringBuffer();
        for (String keyStr : keySet) {
            // if(!"".equals(dataMap.get(keyStr))) {
            sb.append(StringUtils.fieldToColumn(keyStr) + ",");
            // }
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        return sb.toString();
    }

    public long parseTime(String timeStr) {
        Long timeRet = 0l;
        DateTime dateTime = DateUtil.parse(timeStr);
        timeRet = dateTime.getTime();

        return timeRet;

    }

    //通过数据库url查询数据库的模式名称
    private String getSchemaName(String collectDBUrl) {
        if (collectDBUrl != null) {
            String temp = collectDBUrl.substring(0, collectDBUrl.indexOf("?"));
            temp = temp.substring(temp.lastIndexOf("/") + 1);
            return temp;
        }
        return null;
    }

    public static String createPrepared(int num) {
        StringBuffer sb = new StringBuffer(num * 2 + 10);
        for (int i = 0; i < num; i++) {
            sb.append("{" + i + "},");
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        return sb.toString();
    }

    public static String createValue(Set<String> keySet, Map<String, Object> dataMap) {
        StringBuffer sb = new StringBuffer();
        for (String keyStr : keySet) {
            if (!"".equals(dataMap.get(keyStr))) {
                sb.append("'" + dataMap.get(keyStr) + "',");
            }
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        return sb.toString();
    }

    public static String createColumnSql(Set<String> keySet, Map<String, Object> dataMap) {
        StringBuffer sb = new StringBuffer();
        for (String keyStr : keySet) {
            // if(!"".equals(dataMap.get(keyStr))) {
            sb.append(StringUtils.fieldToColumn(keyStr) + ",");
            // }
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        return sb.toString();
    }

    public static String createColumnSqlForCollect(Set<String> keySet, Map<String, Object> dataMap) {
        StringBuffer sb = new StringBuffer();
        for (String keyStr : keySet) {

            // if(!"".equals(dataMap.get(keyStr))) {
            sb.append("`" + keyStr + "`" + ",");
            // }
        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        return sb.toString();
    }

    public static String createColumnUpdateSql(Set<String> keySet, String idColumnName) {
        StringBuffer sb = new StringBuffer();
        int i = 0;
        for (String keyStr : keySet) {
            if (!keyStr.equals(idColumnName)) {
                sb.append(StringUtils.fieldToColumn(keyStr) + "= {" + i + "} ,");
                i++;
            }

        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        return sb.toString();
    }

    public static String createColumnUpdateSqlForCollect(Set<String> keySet, String idColumnName) {
        StringBuffer sb = new StringBuffer();
        int i = 0;
        for (String keyStr : keySet) {
            if (!keyStr.equals(idColumnName)) {
                sb.append("`" + keyStr + "`" + "= {" + i + "} ,");
                i++;
            }

        }
        sb.deleteCharAt(sb.lastIndexOf(","));
        return sb.toString();
    }

    private String getTypeString(String inputString) {
        int index = inputString.lastIndexOf(".");
        String type = null;
        if (index != -1) {
            type = inputString.substring(index + 1);
        } else {
            type = inputString;
        }
        return type.toLowerCase();
    }

    @PostMapping(value = "/testMinio")
    @ApiOperation(value = "系统-信息导入表功能:分页查询列表")
    public BusiResponse testMinio(@RequestBody String importdata) {
        Map<String, Object> dataMap = JSON.parseObject(importdata, Map.class);

        try {
            //listObjects("public", "hifar/plat/03f1732ae3254729a2eb16e08e85c6b2.zip");
            //getMinioFileList("public", "");

            listObjects("private", "/");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("======dataMap======" + dataMap);
        return BusiResponse.ok("成功");

    }

    /**
     * 递归获取某路径下的所有文件，文件夹，并输出
     */
    public void getMinioFileList(String bucketName, String objectName) throws Exception {
        List<String> list = new ArrayList<>(12);
        Iterable<Result<Item>> results = listObjectsNoRecursive(bucketName, objectName);
        Long count = 0l;
        for (Result<Item> result : results) {
            Item item = result.get();
            count++;
            if (item.isDir()) {
                System.out.println("文件夹名：" + item.objectName() + "\t  ");
                getMinioFileList(bucketName, item.objectName());

            } else {
                System.out.println("文件名：" + item.objectName() + "\t 文件大小 ： " + item.size());
            }
        }
        System.out.println("========总条数：count=============" + count);
    }

    public static Iterable<Result<Item>> listObjectsNoRecursive(String buckPre, String objectName) throws Exception {
        if (StringUtils.isEmpty(buckPre)) {
            buckPre = MinioCfgUtils.PRE_DEFAULT;
        }
        String buckName = MinioCfgUtils.getBucketName(buckPre);

        // 条件查询
        Iterable<Result<Item>> listObjects = MinioUtils.getMinioService().getClient()
                .listObjects(ListObjectsArgs.builder().bucket(buckName).prefix(objectName).recursive(false).build());

        return listObjects;

    }

    public static List<Item> listObjects(String buckPre, String objectName) throws Exception {
        if (StringUtils.isEmpty(buckPre)) {
            buckPre = MinioCfgUtils.PRE_DEFAULT;
        }
        String buckName = MinioCfgUtils.getBucketName(buckPre);
        // MinioUtils.getMinioService().getClient().listObjects(null);
        Long count = 0l;
        // 指定桶名称和上传文件的本地路径
        // String bucketName = "buckName";
        // 条件查询
        Iterable<Result<Item>> listObjects = MinioUtils.getMinioService().getClient()
                .listObjects(ListObjectsArgs.builder().bucket(buckName).prefix(objectName).recursive(true) // 递归
                        .build());
        List<Item> itemList = new ArrayList<Item>();
        for (Result<Item> result : listObjects) {
            Item item = result.get();
            itemList.add(item);
            count++;
            if (item.isDir()) {
                System.out.println("====1.文件夹名：" + item.objectName() + "\t  ");
                if (item.lastModified() != null) {
                    ZonedDateTime dateTime = item.lastModified();
                    Instant instant0102 = dateTime.toInstant();
                    Date date0102 = Date.from(instant0102);
                    System.out.println("==文件夹：item= dateTime:==" + DateUtils.formatTime(date0102));
                }
            } else {
                System.out.println("====2.文件名：" + item.objectName() + "\t 文件大小 ： " + item.size());
                if (item.lastModified() != null) {
                    ZonedDateTime dateTime = item.lastModified();
                    Instant instant0102 = dateTime.toInstant();
                    Date date0102 = Date.from(instant0102);
                    System.out.println("==文件：item= dateTime:==" + DateUtils.formatTime(date0102));
                }
            }


        }
        System.out.println("========总条数：count=============" + count);
        return itemList;

    }

    @PostMapping(value = "/listAll")
    @ApiOperation(value = "系统-信息导入表功能:查询列表(不带分页)")
    public BusiResponse listAll(HttpServletRequest request) {
        QueryWrapper<SysSyncImport8357> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("del_flag", "1");
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        List<SysSyncImport8357> list = sysSyncImport8357Service.list(queryWrapper);
        if (list != null && list.size() > 0) {
            return BusiResponse.OK(list);
        } else {
            return BusiResponse.ok("没有查询到数据！");
        }
    }

    @PostMapping(value = "/add")
    @ApiOperation(value = "系统-信息导入表功能:新增")
    public BusiResponse add(@RequestBody SysSyncImport8357 sysSyncImport) {
        sysSyncImport8357Service.save(sysSyncImport);
        return BusiResponse.ok("添加成功");
    }

    @PostMapping(value = "/edit")
    @ApiOperation(value = "系统-信息导入表功能:编辑")
    public BusiResponse edit(@RequestBody SysSyncImport8357 sysSyncImport) {
        sysSyncImport8357Service.updateById(sysSyncImport);
        return BusiResponse.ok("编辑成功！");
    }

    @GetMapping("/queryById")
    @ApiOperation(value = "系统-信息导入表功能:根据id查询数据")
    public BusiResponse queryById(@RequestParam(value = "id") String id) {
        SysSyncImport8357 byId = sysSyncImport8357Service.getById(id);
        // 查询转换附件
        return BusiResponse.OK(byId);
    }

    @PostMapping("/delete")
    @ApiOperation(value = "系统-信息导入表功能:逻辑删除")
    public BusiResponse delete(@RequestBody String id) {
        JSONObject jsonObject = JSON.parseObject(id);
        UpdateWrapper<SysSyncImport8357> delete = new UpdateWrapper<>();
        delete.in("id", jsonObject.getString("id").split(","));
        delete.set("del_flag", "1");
        sysSyncImport8357Service.update(delete);
        return BusiResponse.ok("删除成功！");
    }

    @PostMapping("/exportExcel")
    @ApiOperation(value = "系统-信息导入表功能:导出数据")
    public Object exportExcel(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        if (pageInfo == null) {
            return BusiResponse.error("参数有误！");
        }
        BusiResponse export = sysSyncImport8357Service.exportExcel(pageInfo);
        if (export.getCode() == com.hifar.fw.utils.bean.BusiConst.CODE_SUCCESS) {
            String encode = null;
            try {
                encode = URLEncoder.encode("系统-信息导入表.xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/vnd.ms-excel");
            headers.add("Access-Control-Expose-Headers", "Content-Disposition");
            headers.add("Content-Disposition", "filename=" + encode);
            return ResponseEntity.status(HttpStatus.OK).headers(headers).body((byte[]) export.getData());
        }
        return export;
    }

    @PostMapping("/importExcel")
    @ApiOperation(value = "系统-信息导入表功能:导入excel数据")
    public BusiResponse importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return BusiResponse.error("文件为空！");
        } else {
            if (ExcelTemplateUtil.isExcelFile(file)) {
                return sysSyncImport8357Service.importExcel(file);
            } else {
                return BusiResponse.error("请上传excel文件！");
            }
        }
    }

    //试验系统临时目录
    public static String getTempPathTest() {
        String osName = DataDealUtils.getOsName();
        if (osName.equals("linux")) {
            return "/opt/temp";
        } else if (osName.equals("win")) {
            return "c:" + File.separator + "temp";
        } else {
            return "/opt/temp";
        }
    }

    //调试系统的临时目录
    public static String getTempPathDebug() {
        String osName = DataDealUtils.getOsName();
        if (osName.equals("linux")) {
            return "/opt/tempdebug";
        } else if (osName.equals("win")) {
            return "c:" + File.separator + "tempdebug";
        } else {
            return "/opt/tempdebug";
        }
    }

}